﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Windows;

namespace SangoDesktop
{
	/// <summary>
	/// Delegate that pass xml message to GameHandler.
	/// </summary>
	/// <param name="message"></param>
	public delegate void NewMessage(string message);

	/// <summary>
	/// To send messages to the server and check if there're new messages on the server.
	/// </summary>
	class MessageController
	{
		string guid=null;
		SangoService.ServiceSoapClient serviceClient=new SangoDesktop.SangoService.ServiceSoapClient();

		private event NewMessage ReceiveMessage;

		/// <summary>
		/// Contrustor.
		/// </summary>
		/// <param name="receiveMessage">The method that will be called when a new message from server is received.</param>
		public MessageController ( NewMessage receiveMessage )
		{
			this.ReceiveMessage = receiveMessage;
		}

		/// <summary>
		/// To register in the server and initialize the guid. Used when and only when joining game.
		/// </summary>
		/// <param name="playerName"></param>
		/// <returns>The xml message returned from server.</returns>
		public string Register ( string playerName )
		{
			string r=serviceClient.SendMsg("<message type=\"newuser\"><user>" + playerName + "</user></message>", "");
			XDocument doc = XDocument.Parse(r);
			XElement root = doc.Root;
			if ( root.Attribute("result").Value == "success" )
			{
				this.guid = root.Element("guid").Value;
				( new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(this.getMessage)) ).Start();
			}
			return r;						
		}

		/// <summary>
		/// Send a piece of xml message to server.
		/// </summary>
		/// <param name="message"></param>
		/// <returns></returns>
		public string SendMessage ( string message )
		{
			if ( guid != null && guid != "" )
			{
				return serviceClient.SendMsg(message, guid);
			}
			else
				throw new Exception("guid not initialized");
		}

		private void getMessage (object o )
		{
			if ( guid != null && guid != "" )
			{
				bool flag=true;
				while ( flag )
				{
					string message=serviceClient.GetMsg(guid);
					this.ReceiveMessage(message);
				}
			}
			else
				throw new Exception("guid not initialized");
		}
	}
}
